package org.gwtde.client.controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.mygwt.ui.client.mvc.AppEvent;
import net.mygwt.ui.client.mvc.Controller;
import net.mygwt.ui.client.widget.Shell;
import net.mygwt.ui.client.widget.ToolItem;

import org.gwtde.client.DesktopEvents;
import org.gwtde.client.views.DesktopView;

public class DesktopController extends Controller {

	private DesktopView mDesktopView;

	private List mShellList = new ArrayList();
	private Map mItemMap = new HashMap();

	public DesktopController() {
		registerEventType(DesktopEvents.Init);

		registerEventType(DesktopEvents.ShellOpenURL);
		registerEventType(DesktopEvents.ShellActivated);
		registerEventType(DesktopEvents.ShellDeActivated);
		registerEventType(DesktopEvents.ShellClosed);
		registerEventType(DesktopEvents.ShellCreated);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.mygwt.ui.client.mvc.Controller#handleEvent(net.mygwt.ui.client.mvc.AppEvent)
	 */
	public void handleEvent(AppEvent pEvent) {
		Shell shell;
		ToolItem item;

		switch (pEvent.type) {
		case DesktopEvents.Init:
			forwardToView(mDesktopView, pEvent);
			break;
		case DesktopEvents.ShellCreated:
			shell = (Shell) pEvent.data;
			if (mShellList.indexOf(shell) == -1) {
				mShellList.add(shell);
				item = mDesktopView.add(shell);
				mItemMap.put(shell, item);
				item.setSelected(true);
			}
			break;
		case DesktopEvents.ShellActivated:
			shell = (Shell) pEvent.data;
			if (mShellList.indexOf(shell) != -1) {
				item = (ToolItem) mItemMap.get(shell);
				item.setSelected(true);
			}
			break;
		case DesktopEvents.ShellDeActivated:
			shell = (Shell) pEvent.data;
			if (mShellList.indexOf(shell) != -1) {
				item = (ToolItem) mItemMap.get(shell);
				item.setSelected(false);
			}
			break;
		case DesktopEvents.ShellClosed:
			shell = (Shell) pEvent.data;
			if (mShellList.indexOf(shell) != -1) {
				item = (ToolItem) mItemMap.get(shell);
				mShellList.remove(shell);
				mItemMap.remove(shell);
				mDesktopView.remove(item);
			}
			break;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.mygwt.ui.client.mvc.Controller#initialize()
	 */
	public void initialize() {
		mDesktopView = new DesktopView(this);
	}

}
